package com.shunbo.convenient.controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.shunbo.convenient.service.AndroidService;
import com.shunbo.convenient.service.AreaService;
import com.shunbo.convenient.service.StoreService;
import com.shunbo.convenient.service.UserInfoService;
import com.shunbo.convenient.utils.JsonUtils;
import com.shunbo.convenient.utils.ConvenientResult;
import com.shunbo.convenient.utils.MapUtil;
import com.shunbo.convenient.utils.SmsSend;
import com.shunbo.convenient.vo.AndroidVersion;
import com.shunbo.convenient.vo.Area;
import com.shunbo.convenient.vo.Store;
import com.shunbo.convenient.vo.UserInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * @author weizhuang
 * app
 */
@RestController
@RequestMapping("/app")
public class AppController {


    @Resource
    private UserInfoService userInfoService;

    @Resource
    private StoreService storeService;

    @Resource
    private AndroidService androidService;

    @Resource
    private AreaService areaService;


    /**
     * 短信验证
     *
     * @return Result结果集
     */
    @RequestMapping("/send")
    public ConvenientResult send(@RequestBody UserInfo userInfo) {
        try {
            System.out.println(JsonUtils.objectToJson(userInfo));
            int code = (int) ((Math.random() * 9 + 1) * 100000);
            List<UserInfo> all = userInfoService.findAll(userInfo);
            if (all.size() == 0 && StringUtils.isEmpty(userInfo.getOldMobile())) {
                return ConvenientResult.build(200, "当前手机号没有注册用户", false);
            } else if (all.size() == 0 && !StringUtils.isEmpty(userInfo.getOldMobile())) {
                UserInfo userInfo1 = new UserInfo();
                userInfo1.setMobile(userInfo.getOldMobile());
                List<UserInfo> all1 = userInfoService.findAll(userInfo1);
                if (all1.size() > 0) {
                    SendSmsResponse response = SmsSend.sendSms(userInfo.getMobile(), code);
                    System.out.println(JsonUtils.objectToJson(response));
                    if ("OK".equals(response.getCode())) {
                        userInfo.setId(all1.get(0).getId());
                        userInfo.setMobile(userInfo.getOldMobile());
                        userInfo.setCode(code + "");
                        userInfoService.update(userInfo);
                        return ConvenientResult.build(200, "发送成功", true);
                    } else {
                        return ConvenientResult.build(400, response.getMessage(), false);
                    }
                } else {
                    return ConvenientResult.build(400, "原手机号错误", false);
                }
            } else if (all.size() > 0 && !StringUtils.isEmpty(userInfo.getOldMobile())) {
                return ConvenientResult.build(400, "你要修改的手机号已存在", false);
            } else {
                SendSmsResponse response = SmsSend.sendSms(userInfo.getMobile(), code);
                System.out.println(JsonUtils.objectToJson(response));
                if ("OK".equals(response.getCode())) {
                    userInfo.setId(all.get(0).getId());
                    userInfo.setCode(code + "");
                    userInfoService.update(userInfo);
                    return ConvenientResult.build(200, "发送成功", true);
                } else {
                    return ConvenientResult.build(400, response.getMessage(), false);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ConvenientResult.build(500, "系统错误", e.getStackTrace());
        }
    }

    /**
     * 登录
     *
     * @return Result结果集
     */
    @RequestMapping("/login")
    public ConvenientResult getLogin(@RequestBody UserInfo userInfo) {
        try {

            String token = UUID.randomUUID().toString();
            List<UserInfo> all = userInfoService.findAll(userInfo);
            if (all.size() > 0) {
                Store store = new Store();
                store.setUser_id(all.get(0).getUserId());
                List<Store> stores = storeService.findAll(store);
                if (stores.size() > 0) {
                    all.get(0).setStore(stores.get(0));
                }
                UserInfo uInfo = new UserInfo();
                uInfo.setCode("0");
                uInfo.setId(all.get(0).getId());
                uInfo.setToken(token);
                userInfoService.update(uInfo);
                return ConvenientResult.build(200, "成功", all.get(0));
            } else {
                return ConvenientResult.build(400, "验证码错误", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ConvenientResult.build(500, "系统错误", e.getStackTrace());
        }
    }

    /**
     * 短信验证
     *
     * @return Result结果集
     */
    @RequestMapping("/code")
    public ConvenientResult getCode(@RequestBody UserInfo userInfo) {
        try {
            List<UserInfo> all = userInfoService.findAll(userInfo);
            if (all.size() > 0) {
                UserInfo uInfo = new UserInfo();
                uInfo.setId(all.get(0).getId());
                uInfo.setCode("0");
                userInfoService.update(uInfo);
                return ConvenientResult.build(200, "成功", true);
            } else {
                if (StringUtils.isEmpty(userInfo.getOldMobile())) {
                    return ConvenientResult.build(400, "手机不存在", false);
                }
                userInfo.setMobile(userInfo.getOldMobile());
                all = userInfoService.findAll(userInfo);
                if (all.size() > 0) {
                    UserInfo uInfo = new UserInfo();
                    uInfo.setCode("0");
                    uInfo.setId(all.get(0).getId());
                    userInfoService.update(uInfo);
                    return ConvenientResult.build(200, "成功", true);
                } else {
                    return ConvenientResult.build(400, "手机或者验证码错误", false);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ConvenientResult.build(500, "系统错误", e.getStackTrace());
        }
    }

    /**
     * 获取版本 判断是否强制更新
     *
     * @param version 版本包
     * @return 返回结果标识
     */
    @RequestMapping("/findVersion")
    public ConvenientResult findByMoblie(String version) {

        AndroidVersion av = new AndroidVersion();
        av.setAndroid_version_name(version);
        List<AndroidVersion> list = androidService.findByVersionId(av);
        if (list.size() > 1) {
            return ConvenientResult.build(200, "成功", list.get(0));
        } else {
            return ConvenientResult.build(500, "失败,编号错误", null);
        }
    }

    /**
     * 获取最近的店铺
     *
     * @return Result结果集
     */
    @RequestMapping("/getStore")
    public ConvenientResult getStore(Double lng, Double lat, Integer type, String areaId) {
        try {

            if (type == 1) {
                List<Area> all = areaService.findAll(null);

                Double result = null;

                Integer id = 0;

                for (int i = 0; i < all.size(); i++) {
                    double distance = MapUtil.Distance(lng, lat, Double.parseDouble(all.get(i).getLng()), Double.parseDouble(all.get(i).getLat()));
                    if (result == null) {
                        result = distance;
                        id = i;
                    }
                    if (distance < result) {
                        result = distance;
                        id = i;
                    }
                }

                Store store = new Store();
                store.setAreaId(all.get(id).getId() + "");
                List<Store> all1 = storeService.findAll(store);
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("list", all1);
                resultMap.put("areaName", all.get(id).getName());
                return ConvenientResult.build(200, "成功", resultMap);
            }
            if (type == 2) {

                Area all = areaService.findById(areaId);

                Store store = new Store();
                store.setAreaId(all.getId() + "");
                List<Store> all1 = storeService.findAll(store);
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("list", all1);
                resultMap.put("areaName", all.getName());
                return ConvenientResult.build(200, "成功", resultMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ConvenientResult.build(500, "系统错误", e.getStackTrace());
        }
        return null;
    }

    /**
     * 获取区下的所有门店
     *
     * @return Result结果集
     */
    @RequestMapping("/getStores")
    public ConvenientResult getStores(Area area) {
        try {

            List<Store> stores = new ArrayList<>();
            List<Area> all = areaService.findAll(area);
            for (Area are : all
                    ) {
                Store store = new Store();
                store.setAreaId(are.getId() + "");
                List<Store> all1 = storeService.findAll(store);
                stores.addAll(all1);
            }

            return ConvenientResult.build(200, "成功", stores);
        } catch (Exception e) {
            e.printStackTrace();
            return ConvenientResult.build(500, "系统异常", false);
        }
    }


    /**
     * 上传文件
     *
     * @param files   文件
     * @param request 请求域
     * @return 返回结果标识
     */
    @RequestMapping("/upload")
    public ConvenientResult upload
    (@RequestParam(value = "files", required = false) List<MultipartFile> files, HttpServletRequest request) {
        String filePath = "/home/image/";

        System.out.println(filePath);
        if (files.isEmpty()) {
            return ConvenientResult.build(400, "上传失败，请选择文件", false);
        }
        String name = null;
        try {
            for (MultipartFile file : files
                    ) {
                String fileName = file.getOriginalFilename();
                File dest = new File(filePath + fileName);
                file.transferTo(dest);
                if (name == null) {
                    name = fileName;
                } else {
                    name += "," + fileName;
                }
            }
            return ConvenientResult.build(200, "上传成功", name);
        } catch (Exception e) {
            e.printStackTrace();
            return ConvenientResult.build(500, "上传失败", false);
        }

    }

}
